﻿<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
    exclude-result-prefixes="xsl">
  <xsl:output method="html" omit-xml-declaration="yes" indent="yes"/>

  <xsl:template match="*|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
  </xsl:template>
  <xsl:template match="script[@data-js-app-wp]">

    <xsl:variable name="scriptContent" select="normalize-space(./text())"/>
    <xsl:variable name="scriptContentValue">
      <xsl:call-template name="replace-string">
        <xsl:with-param name="text" select="$scriptContent" />
        <xsl:with-param name="replace" select="'$appContext'" />
        <xsl:with-param name="with" select="'{id:&quot;test-value!&quot;, wpId:&quot;js_app_wp__WPID_&quot;}'"  />
      </xsl:call-template>
    </xsl:variable>

    <script>
      jsAppwebPart.ensure(&quot;_WPID_&quot;);
      <xsl:value-of select="$scriptContentValue" disable-output-escaping="yes"/>
    </script>
  </xsl:template>

  <xsl:template name="replace-string">
    <xsl:param name="text"/>
    <xsl:param name="replace"/>
    <xsl:param name="with"/>
    <xsl:choose>
      <xsl:when test="contains($text,$replace)">
        <xsl:value-of select="substring-before($text,$replace)"/>
        <xsl:value-of select="$with"/>
        <xsl:call-template name="replace-string">
          <xsl:with-param name="text" select="substring-after($text,$replace)"/>
          <xsl:with-param name="replace" select="$replace"/>
          <xsl:with-param name="with" select="$with"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$text" disable-output-escaping="yes"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>


</xsl:stylesheet>